<template>
  <doc-alert title="用户体系" url="https://doc.iocoder.cn/user-center/" />
  <doc-alert title="三方登陆" url="https://doc.iocoder.cn/social-user/" />
  <doc-alert title="Excel 导入导出" url="https://doc.iocoder.cn/excel-import-and-export/" />

  <el-row :gutter="20">
    <!-- 左侧部门树 -->
    <el-col :span="4" :xs="24">
      <ContentWrap class="h-1/1">
        <DeptTree @node-click="handleDeptNodeClick" />
      </ContentWrap>
    </el-col>
    <el-col :span="20" :xs="24">
      <!-- 搜索 -->
      <ContentWrap>
        <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="用户昵称" prop="username">
            <el-input
              v-model="queryParams.username"
              placeholder="请输入用户昵称"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item label="手机号码" prop="mobile">
            <el-input
              v-model="queryParams.mobile"
              placeholder="请输入手机号码"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="用户状态"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间" prop="createTime">
            <el-date-picker
              v-model="queryParams.createTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="datetimerange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery"><Icon icon="ep:search" />搜索</el-button>
            <el-button @click="resetQuery"><Icon icon="ep:refresh" />重置</el-button>
            <el-button
              type="primary"
              plain
              @click="openForm('create')"
              v-hasPermi="['system:user:create']"
            >
              <Icon icon="ep:plus" /> 新增
            </el-button>
            <el-button
              type="warning"
              plain
              @click="handleImport"
              v-hasPermi="['system:user:import']"
            >
              <Icon icon="ep:upload" /> 导入
            </el-button>
            <el-button
              type="success"
              plain
              @click="handleExport"
              :loading="exportLoading"
              v-hasPermi="['system:user:export']"
            >
              <Icon icon="ep:download" />导出
            </el-button>
          </el-form-item>
        </el-form>
      </ContentWrap>
      <ContentWrap>
        <!-- 添加多选时的确认按钮到顶部 -->
        <div v-if="multiple" class="flex mb-4">
          <el-button type="primary" @click="handleConfirm">{{ confirmText }}</el-button>
        </div>

        <el-table
          ref="tableRef"
          v-loading="loading"
          :data="list"
          :row-key="(row) => row.id"
          @row-dblclick="handleRowDblClick"
          @selection-change="handleSelectionChange"
        >
          <el-table-column v-if="multiple" type="selection" width="55" />
          <el-table-column label="用户编号" align="center" key="id" prop="id" />
<!--          <el-table-column-->
<!--            label="用户名称"-->
<!--            align="center"-->
<!--            prop="username"-->
<!--            :show-overflow-tooltip="true"-->
<!--          />-->
          <el-table-column
            label="用户昵称"
            align="center"
            prop="nickname"
            :show-overflow-tooltip="true"
          />
          <el-table-column label="登录手机" align="center" prop="mobile"  />
          <el-table-column
            label="部门"
            align="center"
            key="deptName"
            prop="deptName"
            :show-overflow-tooltip="true"
          />

          <el-table-column label="状态" key="status" width="80">
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                :active-value="0"
                :inactive-value="1"
                @change="handleStatusChange(scope.row)"
                :disabled="!checkPermi(['system:user:update'])"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            :formatter="dateFormatter"
            width="180"
          />
          <el-table-column label="签名" align="center" width="120">
            <template #default="scope">
              <div class="flex items-center justify-center">
                <div
                  v-if="scope.row.sign"
                  class="signature-container"
                  @mouseenter="showSignatureTooltip($event, scope.row.sign)"
                  @mouseleave="hideSignatureTooltip"
                >
                  <el-image
                    :src="scope.row.sign"
                    style="width: 60px; height: 30px"
                    fit="contain"
                    :preview-src-list="[scope.row.sign]"
                    preview-teleported
                  />
                </div>
                <span v-else class="text-gray-400">未签名</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="160">
            <template #default="scope">
              <div class="flex items-center justify-center">
                <el-button
                  type="primary"
                  link
                  @click="handleSignClick(scope.row)"
                  v-hasPermi="['system:user:update']"
                >
                  <Icon icon="ep:edit" />签名
                </el-button>
                <el-button
                  type="primary"
                  link
                  @click="openForm('update', scope.row.id)"
                >
                  <Icon icon="ep:edit" />修改
                </el-button>
                <el-dropdown
                  @command="(command) => handleCommand(command, scope.row)"
                  v-hasPermi="[
                    'system:user:delete',
                    'system:user:update-password',
                    'system:permission:assign-user-role'
                  ]"
                >
                  <el-button type="primary" link><Icon icon="ep:d-arrow-right" /> 更多</el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item
                        command="handleDelete"
                        v-if="checkPermi(['system:user:delete'])"
                      >
                        <Icon icon="ep:delete" />删除
                      </el-dropdown-item>
                      <el-dropdown-item
                        command="handleResetPwd"
                        v-if="checkPermi(['system:user:update-password'])"
                      >
                        <Icon icon="ep:key" />重置密码
                      </el-dropdown-item>
                      <el-dropdown-item
                        command="handleRole"
                        v-if="checkPermi(['system:permission:assign-user-role'])"
                      >
                        <Icon icon="ep:circle-check" />分配角色
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="handlePagination"
        />
      </ContentWrap>

    </el-col>
  </el-row>
  <!-- 签名弹窗 -->
  <el-dialog
    v-model="showSignDialog"
    :before-close="handleCloseSignDialog"
    :title="`签名【${currentSignItem?.nickname || ''}】`"
  >
    <SignaturePad
      ref="signaturePadRef"
      :key="currentSignItem?.id || 0"
      :model-value="currentSignItem?.sign || ''"
      :nickname="currentSignItem?.nickname || ''"
      :id="currentSignItem?.id || ''"
      :width="810"
      :height="450"
      @save="handleSignConfirm"
      @close-dialog="handleSignCancel"
    />
  </el-dialog>
  <!-- 添加或修改用户对话框 -->
  <UserForm ref="formRef" @success="getList" />
  <!-- 用户导入对话框 -->
  <UserImportForm ref="importFormRef" @success="getList" />
  <!-- 分配角色 -->
  <UserAssignRoleForm ref="assignRoleFormRef" @success="getList" />
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { checkPermi } from '@/utils/permission'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { CommonStatusEnum } from '@/utils/constants'
import * as UserApi from '@/api/system/user'
import UserForm from './UserForm.vue'
import UserImportForm from './UserImportForm.vue'
import UserAssignRoleForm from './UserAssignRoleForm.vue'
import DeptTree from './DeptTree.vue'
import { PropType, ref } from 'vue'
import SignaturePad from '@/views/project/list/SignaturePad.vue'
import { ElMessage } from 'element-plus'
defineOptions({ name: 'SystemUser' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref<UserApi.UserVO[]>([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  username: undefined,
  mobile: undefined,
  status: undefined,
  deptId: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const showTableDialog = ref(false)
const showSignDialog = ref(false)
const currentSignItem = ref<any>(null) // 当前签名的用户项
const signaturePadRef = ref() // SignaturePad组件引用

// 签名提示框相关
const signatureTooltip = ref<HTMLElement | null>(null)
const tooltipVisible = ref(false)
// 添加props定义
const props = defineProps({
  selectable: {
    type: Boolean,
    default: false
  },
  multiple: {
    type: Boolean,
    default: false
  },
  confirmText: {
    type: String,
    default: '添加调查人员'
  },
  // 添加默认选中的用户ID列表
  defaultSelectedIds: {
    type: Array as PropType<Array<string>>,
    default: () => []
  }
})


// 修改 emit 定义
const emit = defineEmits(['select', 'cancel'])

// 多选相关
const selectedUsers = ref<any[]>([])

// 添加全局选中用户ID集合
const globalSelectedIds = ref<Set<number>>(new Set())

// 获取当前页面的用户ID列表
const getCurrentPageIds = () => {
  return list.value.map((item) => item.id)
}

// 添加一个标记，用于判断是否正在翻页
const isPaging = ref(false)


// 处理签名点击
const handleSignClick = (row: any) => {
  currentSignItem.value = row
  showSignDialog.value = true
}

// 处理关闭签名弹窗
const handleCloseSignDialog = () => {
  showSignDialog.value = false
  currentSignItem.value = null
}

const handleSignConfirm = async (signatureDataUrl: string) => {
  if (!currentSignItem.value) return

  try {
    // 更新用户的签名字段
    await UserApi.updateUser({
      ...currentSignItem.value,
      sign: signatureDataUrl
    })

    // 更新本地列表中的数据
    const index = list.value.findIndex(item => item.id === currentSignItem.value.id)
    if (index !== -1) {
      list.value[index].sign = signatureDataUrl
    }

    message.success('签名保存成功')
    showSignDialog.value = false
    currentSignItem.value = null
  } catch (error) {
    console.error('保存签名失败:', error)
    message.error('保存签名失败')
  }
}

const handleSignCancel = () => {
  showSignDialog.value = false
  currentSignItem.value = null
}

// 显示签名提示框
const showSignatureTooltip = (event: MouseEvent, signUrl: string) => {
  // 移除已存在的提示框
  hideSignatureTooltip()

  // 创建提示框元素
  const tooltip = document.createElement('div')
  tooltip.className = 'signature-tooltip'
  tooltip.innerHTML = `
    <img src="${signUrl}" alt="签名" style="max-width: 200px; max-height: 150px; object-fit: contain;" />
  `

  // 设置提示框位置
  const rect = (event.target as HTMLElement).getBoundingClientRect()
  tooltip.style.position = 'fixed'
  tooltip.style.left = rect.right + 10 + 'px'
  tooltip.style.top = rect.top + 'px'
  tooltip.style.zIndex = '9999'

  // 添加到页面
  document.body.appendChild(tooltip)
  signatureTooltip.value = tooltip
  tooltipVisible.value = true
}

// 隐藏签名提示框
const hideSignatureTooltip = () => {
  if (signatureTooltip.value) {
    document.body.removeChild(signatureTooltip.value)
    signatureTooltip.value = null
  }
  tooltipVisible.value = false
}


/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await UserApi.getUserPage(queryParams)
    list.value = data.list
    total.value = data.total

    // 在数据加载完成后，设置表格选中状态
    if (props.multiple) {
      nextTick(() => {
        setTableSelection()
      })
    }
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 处理部门被点击 */
const handleDeptNodeClick = async (row) => {
  queryParams.deptId = row.id
  await getList()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 用户导入 */
const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}

/** 修改用户状态 */
const handleStatusChange = async (row: UserApi.UserVO) => {
  try {
    // 修改状态的二次确认
    const text = row.status === CommonStatusEnum.ENABLE ? '启用' : '停用'
    await message.confirm('确认要"' + text + '""' + row.username + '"用户吗?')
    // 发起修改状态
    await UserApi.updateUserStatus(row.id, row.status)
    // 刷新列表
    await getList()
  } catch {
    // 取消后，进行恢复按钮
    row.status =
      row.status === CommonStatusEnum.ENABLE ? CommonStatusEnum.DISABLE : CommonStatusEnum.ENABLE
  }
}

/** 导出按钮操作 */
const exportLoading = ref(false)
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await UserApi.exportUser(queryParams)
    download.excel(data, '用户数据.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 操作分发 */
const handleCommand = (command: string, row: UserApi.UserVO) => {
  switch (command) {
    case 'handleDelete':
      handleDelete(row.id)
      break
    case 'handleResetPwd':
      handleResetPwd(row)
      break
    case 'handleRole':
      handleRole(row)
      break
    default:
      break
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await UserApi.deleteUser(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 重置密码 */
const handleResetPwd = async (row: UserApi.UserVO) => {
  try {
    // 重置的二次确认
    const result = await message.prompt(
      '请输入"' + row.username + '"的新密码',
      t('common.reminder')
    )
    const password = result.value
    // 发起重置
    await UserApi.resetUserPwd(row.id, password)
    message.success('修改成功，新密码是：' + password)
  } catch {}
}

/** 分配角色 */
const assignRoleFormRef = ref()
const handleRole = (row: UserApi.UserVO) => {
  assignRoleFormRef.value.open(row)
}

/** 设置表格选中状态 */
const setTableSelection = () => {
  const table = tableRef.value
  if (table) {
    console.log('开始设置表格选中状态')
    console.log('当前全局选中ID:', Array.from(globalSelectedIds.value))

    // 先清除当前页的选中状态
    table.clearSelection()

    // 找出当前页面中应该被选中的行
    const currentPageSelectedRows = list.value.filter((row) =>
      globalSelectedIds.value.has(Number(row.id))
    )
    console.log('当前页面需要选中的行:', currentPageSelectedRows)

    // 选中这些行
    currentPageSelectedRows.forEach((row) => {
      console.log('正在选中行:', row.id)
      table.toggleRowSelection(row, true)
    })
  }
}

/** 处理多选变化 */
const handleSelectionChange = (selection: any[]) => {
  // 如果是翻页触发的选择变化，则不处理
  if (isPaging.value) {
    return
  }

  console.log('选择变化 - 当前选中行:', selection)

  // 获取当前页面所有行的ID
  const currentPageIds = getCurrentPageIds()
  console.log('当前页面所有ID:', currentPageIds)

  // 获取当前页面选中的行的ID
  const currentPageSelectedIds = selection.map((item) => Number(item.id))
  console.log('当前页面选中的ID:', currentPageSelectedIds)

  // 找出当前页面中新增选中和取消选中的ID
  currentPageIds.forEach((id) => {
    const numId = Number(id)
    const wasSelected = globalSelectedIds.value.has(numId)
    const isSelected = currentPageSelectedIds.includes(numId)

    if (!wasSelected && isSelected) {
      // 新增选中
      console.log('新增选中ID:', numId)
      globalSelectedIds.value.add(numId)
    } else if (wasSelected && !isSelected) {
      // 取消选中
      console.log('取消选中ID:', numId)
      globalSelectedIds.value.delete(numId)
    }
  })

  console.log('全局选中ID集合:', Array.from(globalSelectedIds.value))
}

/** 处理翻页 */
const handlePagination = () => {
  console.log('翻页 - 当前全局选中ID:', Array.from(globalSelectedIds.value))
  // 设置翻页标记
  isPaging.value = true

  getList().then(() => {
    // 在新页面数据加载完成后，设置选中状态
    nextTick(() => {
      setTableSelection()
      // 重置翻页标记
      isPaging.value = false
    })
  })
}

/** 修改双击行为，仅在单选时生效 */
const handleRowDblClick = (row) => {
  if (props.selectable && !props.multiple) {
    emit('select', row)
  }
}

/** 多选确认 */
const handleConfirm = async () => {
  console.log('确认选择 - 全局选中ID:', Array.from(globalSelectedIds.value))

  try {
    // 获取所有选中用户的完整信息
    const selectedIds = Array.from(globalSelectedIds.value)
    if (selectedIds.length === 0) {
      message.warning('请至少选择一个人员')
      return
    }

    // 获取所有选中用户的详细信息
    const selectedUsers = []
    for (const id of selectedIds) {
      try {
        const userInfo = await UserApi.getUser(id)
        selectedUsers.push(userInfo)
      } catch (error) {
        console.error('获取用户信息失败:', error)
      }
    }

    console.log('确认选择 - 选中用户列表:', selectedUsers)

    // 发送所有选中的用户列表
    emit('select', selectedUsers)
  } catch (error) {
    console.error('处理选中用户失败:', error)
    message.error('获取选中用户信息失败')
  }
}

/** 初始化 */
onMounted(() => {
  getList().then(() => {
    // 在列表数据加载完成后，设置默认选中状态
    if (props.multiple && props.defaultSelectedIds?.length > 0) {
      console.log('初始化时收到的默认选中ID:', props.defaultSelectedIds)
      // 初始化全局选中状态
      globalSelectedIds.value = new Set(props.defaultSelectedIds.map((id) => Number(id)))
      console.log('初始化后的全局选中状态:', Array.from(globalSelectedIds.value))

      // 设置表格选中状态
      nextTick(() => {
        // 设置标记，防止handleSelectionChange清空选中状态
        isPaging.value = true
        setTableSelection()
        // 延迟重置标记，确保选中状态已经设置完成
        setTimeout(() => {
          isPaging.value = false
        }, 100)
      })
    }
  })
})

// 添加表格ref
const tableRef = ref()
</script>

<style scoped>
.signature-container {
  cursor: pointer;
  position: relative;
}

.signature-container:hover {
  opacity: 0.8;
}
</style>

<style>
.signature-tooltip {
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 8px;
  max-width: 220px;
  animation: fadeIn 0.2s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
